package com.huawei.petapp2.address.manage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Looper;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huawei.petapp2.R;
import com.huawei.petapp2.activity.HomeActivity;
import com.huawei.petapp2.activity.widget.BaseActivity;
import com.huawei.petapp2.activity.widget.wrapper.ProgressWrapper;
import com.huawei.petapp2.activity.widget.wrapper.ToastWrapper;
import com.huawei.petapp2.address.edit.EditAddressActivity;
import com.huawei.petapp2.constant.HttpUrl;
import com.huawei.petapp2.entity.Address;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.network.UserManager;
import com.huawei.petapp2.network.api.ApiAddressInfo;
import com.huawei.petapp2.network.core.ApiPath;
import com.huawei.petapp2.network.core.ResponseEntity;
import com.huawei.petapp2.network.event.AddressEvent;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.PreferenceHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 管理收货地址.
 */
public class ManageAddressActivity extends BaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.standard_order_title)
    android.widget.TextView TextView;

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.standard_toolbar_back)
    ImageView imageView;

    private ProgressWrapper mProgressWrapper;
    private AddressAdapter mAddressAdapter;
    private List<Address>addresses;

    private Address Comaddress;
    private PreferenceHelper preferenceHelper;
    int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
    String token=PreferenceHelper.getString("token",Objects.requireNonNull(getContext()));
    final private static Gson gson=new GsonBuilder().serializeNulls().create();


    protected int getContentViewLayout() {
        return R.layout.activity_manage_address;
    }


    @Override
    protected int setLayoutId() {
        return R.layout.activity_manage_address;
    }


    @Override
    public void initView() {
       // new ToolbarWrapper(this).setCustomTitle(R.string.address_title_manage);

        mProgressWrapper = new ProgressWrapper();
        mAddressAdapter = new AddressAdapterImpl();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAddressAdapter);
    }

    public void getTest(){
        //get请求
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url("http://192.168.43.55:8080"+"/useraddr/list/1")
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();//增加部分
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                  Result result=gson.fromJson(results,Result.class);
                    System.out.println("新的post请求"+result);
                }
                Looper.loop();//增加部分
            }
        });
    }

    @Override
    public void initData() {
        Result result=new Result();
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()//获取改用户全部地址
                .url(HttpUrl.getBaseUrl()+"/useraddr/list/"+userid)
                .addHeader("Token",token)
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();//增加部分
                if(response.code() >= 200 && response.code() < 300) {
                    String results = response.body().string();
                    Result result=gson.fromJson(results,Result.class);
                    addresses=DateUtil.getList7(result);
                    mProgressWrapper.dismissProgress();
                    mAddressAdapter.reset(addresses);
                    System.out.println("新的post请求"+result);
                }
                Looper.loop();//增加部分
            }
        });

        /* DateUtil.insert(
                HttpAddress.get(HttpAddress.UserAddress(),"getAddr",userid,token));//获取所有地址
        addresses=DateUtil.getList7(result);
        System.out.println(addresses);*/
    }

    //不知道为啥，toolbar自带的点击方法在这里失效，只能用动态绑定的方法
    @OnClick(R.id.standard_toolbar_back) void backAddress() {
        System.out.println("我点到了哦！");
        Intent intent=new Intent(context, HomeActivity.class);
        startActivity(intent);
    }

    @Override
    public void initEvent() {
        mProgressWrapper.dismissProgress();
        mAddressAdapter.reset(addresses);

        System.out.println("现在的addresses"+addresses);
    }


    @Override
    protected void onBusinessResponse(String apiPath, boolean success, ResponseEntity rsp) {
        switch (apiPath) {
            case ApiPath.ADDRESS_DEFAULT:
            case ApiPath.ADDRESS_DELETE:
                if (success) {
                    UserManager.getInstance().retrieveAddressList();
                } else {
                    mProgressWrapper.dismissProgress();
                }
                break;
            case ApiPath.ADDRESS_INFO:
                mProgressWrapper.dismissProgress();
                if (success) {
                    ApiAddressInfo.Rsp infoRsp = (ApiAddressInfo.Rsp) rsp;
                    Intent intent = EditAddressActivity.getStartIntent(this, infoRsp.getData());
                    startActivity(intent);
                }
                break;
            default:
                throw new UnsupportedOperationException(apiPath);
        }
    }


    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(AddressEvent event) {
        mProgressWrapper.dismissProgress();
        mAddressAdapter.reset(addresses);
    }

    @OnClick(R.id.button_create) void navigateToAddAddress() {
        Intent intent = EditAddressActivity.getStartIntent(this, null);
        startActivity(intent);
    }

    private class AddressAdapterImpl extends AddressAdapter {
        @Override
        protected void onSetDefault(Address address) {
            mProgressWrapper.showProgress(ManageAddressActivity.this);
            //获取收获地址
            Result result=new Result();
            OkHttpClient client = new OkHttpClient();

            System.out.println("设置新的默认地址"+address.getAddrId());
            Request request1 = new Request.Builder()
                    .url(HttpUrl.getBaseUrl()+"/useraddr/updateCom/"+userid+"/"+address.getAddrId())
                    .addHeader("Token",token)
                    .build();

            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Looper.prepare();//增加部分
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("设置新的默认地址的数组"+addresses);
                        addresses=DateUtil.getList7(result);
                        ToastWrapper.show(R.string.address_action_set_default);
                        System.out.println("设置新的默认地址"+result);
                    }
                    Looper.loop();//增加部分
                }

            });
            //刷新当前activity
            preferenceHelper.saveDefalue(getContext(),String.valueOf(address.getAddrId()),address.getReceiverName(),
                    address.getReceiverMobile(),address.getAddr(),address.getProvince(),address.getCity(),address.getArea());
            Intent intent=new Intent(ManageAddressActivity.this,ManageAddressActivity.class);
            startActivity(intent);
        }







        @Override
        protected void onDelete(Address address) {
            /*if (address.getCommonAddr()==1) {
                ToastWrapper.show(R.string.address_msg_can_not_delete_default);
                return;
            }*/


            mProgressWrapper.showProgress(ManageAddressActivity.this);
            //删除默认地址

            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()
                    .url(HttpUrl.getBaseUrl()+"/useraddr/delete/"+address.getAddrId())
                    .addHeader("Token",token)
                    .build();
            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Looper.prepare();//增加部分
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的修改地址请求"+result);
                    }
                    Looper.loop();//增加部分
                }
            });
            Intent intent = new Intent(getContext(),ManageAddressActivity.class);
            startActivity(intent);

        }

        @Override
        protected void onEdit(Address address) {
            mProgressWrapper.showProgress(ManageAddressActivity.this);
            int userid= PreferenceHelper.getInt("userId", Objects.requireNonNull(getContext()));
            //更新用户地址，或者创建用户地址
            //post
            OkHttpClient client = new OkHttpClient();
            Request request1 = new Request.Builder()
                    .url(HttpUrl.getBaseUrl()+"/useraddr/insert/"+userid+"/"+address.getAddrId()+"/"+address.getReceiverName()+"/"+
                            address.getReceiverMobile()+"/"+ address.getProvince()+"/"+address.getCity()+"/"+address.getArea()+"/"+address.getAddr()+"/"+address.getPostCode())
                    .addHeader("Token",token)
                    .build();
            client.newCall(request1).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Looper.prepare();//增加部分
                    if(response.code() >= 200 && response.code() < 300) {
                        String results = response.body().string();
                        Result result=gson.fromJson(results,Result.class);
                        System.out.println("新的post请求"+result);
                    }
                    Looper.loop();//增加部分
                }
            });
            Intent intent = EditAddressActivity.getStartIntent(getContext(), address);
            startActivity(intent);
        }

    }

}
